package com.example.myjavafx.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import java.io.ByteArrayInputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;

// ImageController.java
public class ImageController {
    @FXML
    private ImageView imageView;

    private final HttpClient client = HttpClient.newHttpClient();

    @FXML
    private void fetchImage() {
        Task<Image> task = new Task<>() {
            @Override
            protected Image call() throws Exception {
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create("http://localhost:5000/capture"))
                        .build();

                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                String json = response.body();

                // 解析JSON获取Base64图像数据
                ObjectMapper mapper = new ObjectMapper();
                JsonNode node = mapper.readTree(json);
                String base64Image = node.get("image").asText();

                // 解码Base64为字节数组
                byte[] imageData = Base64.getDecoder().decode(base64Image);
                return new Image(new ByteArrayInputStream(imageData));
            }
        };

        task.setOnSucceeded(e -> imageView.setImage(task.getValue()));
        task.setOnFailed(e -> showError("加载失败: " + task.getException().getMessage()));

        new Thread(task).start();
    }

    private void showError(String message) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setContentText(message);
            alert.show();
        });
    }
}